import { Menu, Icon, Card, Form, TimePicker, DatePicker, Select, Input, Button, Table, Pagination, InputNumber  } from "antd";
import moment from "moment";
import React from "react";
import { formatMessage } from 'umi-plugin-react/locale';
import { workOrderProcessingList } from "@/services/workOrder";
import UserSession from "@/UserSession";
import ProcessingDetail from "../workOrderProcessing/processingDetail";
import { adminList } from "@/services/userProfile";
import { selfBuiltList } from "@/services/aigcUser";

class WorkOrderAllocate extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      type:'1',
      loading:false,
      current:1,
      size:10,
      total:0,
      list:[],
      userList:[]
    }
  }

  componentDidMount(){
    this.getList()
    this.getUserList()
  }

  getUserList = async () => {
    let userList = []
    if(UserSession.getCurrentUser().isAdmin){
      //甲方管理员
      const res = await adminList({current:1,size:999999,applicationId:UserSession.getCurrentUser().applicationId})
      userList =res.records
    }else{
      //乙方
      const res = await selfBuiltList({current:1,size:999999,categoryId:"",name:""})
      userList =res.records
    }
    
    this.setState({userList})
  }

  getList = () => {
    this.setState({
      loading:true,
    },async () => {
      const { current,size,type } = this.state;
      const formInfo = this.props.form.getFieldsValue()
      let orderFlag = UserSession.isAdmin ? 0 : 1
      if(type == -1){
        orderFlag = null
      }
      let obj = {
        current,
        size,
        search:formInfo.search,
        processUser:formInfo.processUser,
        startDate:formInfo.time && formInfo.time[0] ? moment(formInfo.time[0]).format("YYYY-MM-DD") : '',
        endDate:formInfo.time && formInfo.time[1] ? moment(formInfo.time[1]).format("YYYY-MM-DD") : '',
        ticketStatus:type == -1 ? null : parseInt(type),
        applicationId:UserSession.getCurrentUser().applicationId,
        orderFlag
      }
      console.log('查询入参=======',obj);
      const res = await workOrderProcessingList(obj)
      
      this.setState({
        loading:false,
        list:res.records,
        total:res.total
      })
    })
  }

  doSearch = (current,size) => {
    this.setState({current,size},() => {
      this.getList()
    })
  }

  /**
   * 
   * @param {*} row 表格记录数据
   * @param {*} readonly 是否只读 true只读
   * @param {*} allocatedDisabled 是否禁用分配按钮 true禁用
   * @param {*} replayDisabled 是否禁用回复按钮 true禁用
   * @param {*} isAllocated 是否指派页面打开的 指派可以转甲乙方需要调新接口
   */
  openDetail = (row,readonly,allocatedDisabled,replayDisabled,isAllocated) => {
    this.ProcessingDetail.initData(row.id,readonly,allocatedDisabled,replayDisabled,isAllocated)
  }

  handleClick = e => {
    this.setState({type:e.key},this.doSearch(1,this.state.size))
    
  }

  render(){
    const { type,current,size,list,total,loading,userList } = this.state;
    const { form:{getFieldDecorator} } = this.props;
    
    let columns = [
      {
        title:formatMessage({id:'pages.workOrder.allocate.orderNum'}),
        dataIndex:"orderNum",
        width:150,
      },
      {
        title:formatMessage({id:'pages.workOrder.allocate.content'}),
        dataIndex:"content",
        width:200,
      },
      {
        title:formatMessage({id:'pages.workOrder.allocate.submitter'}),
        dataIndex:"submitUser",
        width:150,
      },
      // {
      //   title:formatMessage({id:'pages.workOrder.allocate.processor'}),
      //   dataIndex:"processUser",
      //   width:150,
      // },
      {
        title:formatMessage({id:'pages.workOrder.allocate.submitTime'}),
        dataIndex:"createTime",
        width:150,
        render(time){
          return time ? moment(time).format("YYYY-MM-DD HH:mm:ss") : ''
        }
      },
      {
        title:formatMessage({id:'pages.workOrder.allocate.lastProcessTime'}),
        dataIndex:"lastProcessTime",
        width:150,
        render(time){
          return time ? moment(time).format("YYYY-MM-DD HH:mm:ss") : ''
        }
      },
    ]

    //待分配
    if(type == 1){
      columns.push({
        title:formatMessage({id:'pages.workOrder.allocate.action'}),
        width:100,
        align:"center",
        render:(item,row) => {
          return row.ableTransfer ? (
            <Button type="link" onClick={() => this.openDetail(row,false,false,true,true)} >{formatMessage({id:'pages.workOrder.allocate.allocate'})}</Button>
          ) : (
            <Button type="link" onClick={() => this.openDetail(row,true,true,true)}>{formatMessage({id:'pages.workOrder.allocate.view'})}</Button>
          )
        }
      })
    }

    //待处理
    if(type == 2){
      columns.splice(3, 0, {
        title:formatMessage({id:'pages.workOrder.allocate.pendingProcessor'}),
        dataIndex:"unProcessedUsers",
        width:150
      });
    }

    //处理中
    if(type == 3 || type == 2){
      columns.push({
        title:formatMessage({id:'pages.workOrder.allocate.action'}),
        width:100,
        align:"center",
        render:(item,row) => {
          return row.ableTransfer ? (
            <Button type="link" onClick={() => this.openDetail(row,false,false,true)} disabled={!row.ableTransfer}>{formatMessage({id:'pages.workOrder.allocate.reallocate'})}</Button>
          ) : <Button type="link" onClick={() => this.openDetail(row,true,true,true)}>{formatMessage({id:'pages.workOrder.allocate.view'})}</Button>
        }
      })
    }

    //全部
    if(type == -1){
      columns.splice(3, 0, {
        title:formatMessage({id:'pages.workOrder.allocate.processor'}),
        dataIndex:"orderFlag",
        width:150,
        render:orderFlag => {
          return orderFlag == 0 ? formatMessage({id:'pages.workOrder.allocate.company'}) : formatMessage({id:'pages.workOrder.allocate.serviceProvider'})
        }
      });
      columns.splice(5, 0, {
        title:formatMessage({id:'pages.workOrder.allocate.status'}),
        dataIndex:"ticketStatus",
        width:150,
        render:status => {
          return status == 1 ? formatMessage({id:'pages.workOrder.allocate.pendingAllocation'}) : 
                 status == 2 ? formatMessage({id:'pages.workOrder.allocate.pendingProcessing'}) : 
                 status == 3 ? formatMessage({id:'pages.workOrder.allocate.processing'}) : 
                 status == 4 ? formatMessage({id:'pages.workOrder.allocate.closed'}) : 
                 status == 5 ? formatMessage({id:'pages.workOrder.allocate.canceled'}) : ''
        }
      },{
        title:formatMessage({id:'pages.workOrder.allocate.companyProcessTime'}),
        dataIndex:"solutionDurationJiafang",
        width:100,
      },{
        title:formatMessage({id:'pages.workOrder.allocate.serviceProcessTime'}),
        dataIndex:"solutionDurationYifang",
        width:100,
      });
      columns.push({
        title:formatMessage({id:'pages.workOrder.allocate.action'}),
        width:100,
        align:"center",
        render:(item,row) => {
          return <Button type="link" onClick={() => this.openDetail(row,true,true,true)}>{formatMessage({id:'pages.workOrder.allocate.view'})}</Button>
        }
      })
    }


    return(
      <Card bordered={false} style={{height:"100%"}}>
        <Menu onClick={this.handleClick} selectedKeys={[type]} mode="horizontal">
          <Menu.Item key={'1'}>{formatMessage({id:'pages.workOrder.allocate.pendingAllocation'})}</Menu.Item>
          <Menu.Item key={'2'}>{formatMessage({id:'pages.workOrder.allocate.pendingProcessing'})}</Menu.Item>
          <Menu.Item key={'3'}>{formatMessage({id:'pages.workOrder.allocate.processing'})}</Menu.Item>
          <Menu.Item key={'-1'}>{formatMessage({id:'pages.workOrder.allocate.all'})}</Menu.Item>
        </Menu>

        <Form layout="inline" style={{margin:"20px 0"}}>
          <Form.Item>
            {getFieldDecorator("time")(<DatePicker.RangePicker style={{width:250}} />)}
          </Form.Item>
          <Form.Item>
            {getFieldDecorator("processUser")(
              <Select placeholder={formatMessage({id:'pages.workOrder.allocate.selectEngineer'})} style={{width:250}}>
                <Select.Option value={null}>{formatMessage({id:'pages.workOrder.allocate.all'})}</Select.Option>
                {
                  userList.map(item => (
                    <Select.Option value={item.id} key={item.id} title={item.name || item.userName}>{item.name || item.userName}</Select.Option>
                  ))
                }
              </Select>
            )}
          </Form.Item>
          <Form.Item>
            {getFieldDecorator("search")(<Input.Search placeholder={formatMessage({id:'pages.workOrder.allocate.searchPlaceholder'})} style={{width:250}} onSearch={() => this.doSearch(1,size)} />)}
          </Form.Item>
          <Form.Item><Button type="primary" onClick={() => this.doSearch(1,size)}>{formatMessage({id:'pages.workOrder.allocate.search'})}</Button></Form.Item>
        </Form>

        <Table 
          columns={columns}
          dataSource={list}
          rowKey={'id'}
          loading={loading}
          pagination={false}
          scroll={{x:"auto"}}
        />

        {
          total < (size + 1) ? '' : (
            <Pagination 
              current={current}
              pageSize={size}
              total={total}
              showQuickJumper={true}
              onChange={this.doSearch}
            />
          )
        }

        
        <ProcessingDetail onRef={ref => this.ProcessingDetail = ref} refreshList={() => this.doSearch(1,size)} />
      </Card>
    )
  }
}

export default Form.create()(WorkOrderAllocate)